<template>
  <div class="tech-dashboard">
    <!-- 加载状态 -->
    <div v-if="isLoading" class="dashboard-loading">
      <div class="loading-content">
        <div class="loading-spinner-container">
          <div class="loading-spinner">
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-ring"></div>
            <div class="spinner-core">
              <i class="fa fa-rocket"></i>
            </div>
          </div>
        </div>
        <div class="loading-text">
          <span class="text-glow">曾老湿就快好了</span>
          <span class="dots">
            <span class="dot">.</span>
            <span class="dot">.</span>
            <span class="dot">.</span>
          </span>
        </div>
        <div class="loading-progress">
          <div class="progress-bar" :style="{ width: loadingProgress + '%' }">
            <div class="progress-glow"></div>
          </div>
          <div class="progress-text">{{ loadingProgress }}%</div>
        </div>
      </div>
    </div>

    <!-- 主要内容 -->
    <div class="dashboard-content" :style="{ opacity: isLoading ? 0 : 1, transition: 'opacity 0.5s ease' }">
    <!-- 页面标题 -->
    <div class="dashboard-header starry-background">
      <h1 class="dashboard-title">
        <i class="fa fa-tachometer-alt"></i>
        系统监控仪表盘
      </h1>
      <div class="dashboard-subtitle">实时监控系统状态 · 数据驱动决策</div>
      <div class="last-update">
        <i class="fa fa-clock"></i>
        最后更新: {{ lastUpdateTime }}
      </div>
    </div>

    <!-- 赛车仪表盘区域 -->
    <div class="gauges-section">
      <div class="section-title">
        <i class="fa fa-microchip"></i>
        系统核心指标
      </div>
      <div class="gauges-container">
        <div class="gauge-item">
          <div class="gauge-wrapper starry-background">
            <div ref="cpuGaugeRef" class="gauge-chart"></div>
            <div class="gauge-info">
              <div class="gauge-details">
                <div class="detail-item">
                  <span class="detail-label">已使用:</span>
                  <span class="detail-value">{{ systemMetrics.cpuUsed || '0' }}核</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">总计:</span>
                  <span class="detail-value">{{ systemMetrics.cpuTotal || '0' }}核</span>
                </div>
              </div>
              <div class="gauge-status" :class="getStatusClass(systemMetrics.cpu)">
                {{ getStatusText(systemMetrics.cpu) }}
              </div>
            </div>
          </div>
        </div>

        <div class="gauge-item">
          <div class="gauge-wrapper starry-background">
            <div ref="memoryGaugeRef" class="gauge-chart"></div>
            <div class="gauge-info">
              <div class="gauge-details">
                <div class="detail-item">
                  <span class="detail-label">已使用:</span>
                  <span class="detail-value">{{ systemMetrics.memoryUsed || '0GB' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">总计:</span>
                  <span class="detail-value">{{ systemMetrics.memoryTotal || '0GB' }}</span>
                </div>
              </div>
              <div class="gauge-status" :class="getStatusClass(systemMetrics.memory)">
                {{ getStatusText(systemMetrics.memory) }}
              </div>
            </div>
          </div>
        </div>

        <div class="gauge-item">
          <div class="gauge-wrapper starry-background">
            <div ref="diskGaugeRef" class="gauge-chart"></div>
            <div class="gauge-info">
              <div class="gauge-details">
                <div class="detail-item">
                  <span class="detail-label">已使用:</span>
                  <span class="detail-value">{{ systemMetrics.diskUsed || '0GB' }}</span>
                </div>
                <div class="detail-item">
                  <span class="detail-label">总计:</span>
                  <span class="detail-value">{{ systemMetrics.diskTotal || '0GB' }}</span>
                </div>
              </div>
              <div class="gauge-status" :class="getStatusClass(systemMetrics.disk)">
                {{ getStatusText(systemMetrics.disk) }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片区域 -->
    <div class="stats-section">
      <div class="section-title">
        <i class="fa fa-chart-bar"></i>
        关键业务指标
      </div>
      <div class="stats-grid">
        <div class="stat-card starry-background" v-for="(stat, index) in businessStats" :key="index">
          <div class="stat-icon">
            <i :class="stat.icon"></i>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ stat.value }}</div>
            <div class="stat-label">{{ stat.label }}</div>
            <div class="stat-trend" :class="stat.trend">
              <i :class="stat.trendIcon"></i>
              {{ stat.trendText }}
            </div>
          </div>
          <div class="stat-chart">
            <canvas :ref="el => statChartRefs[index] = el" class="mini-chart"></canvas>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <!-- 系统性能趋势图 -->
        <el-col :span="12">
          <div class="chart-card starry-background">
            <div class="chart-header">
              <h3>
                <i class="fa fa-line-chart"></i>
                系统性能趋势
              </h3>
              <div class="chart-controls">
                <el-button-group size="small">
                  <el-button :type="timeRange === '1h' ? 'primary' : ''" @click="setTimeRange('1h')">1小时</el-button>
                  <el-button :type="timeRange === '6h' ? 'primary' : ''" @click="setTimeRange('6h')">6小时</el-button>
                  <el-button :type="timeRange === '24h' ? 'primary' : ''" @click="setTimeRange('24h')">24小时</el-button>
                </el-button-group>
              </div>
            </div>
            <div class="chart-content">
              <canvas ref="performanceChartRef" class="performance-chart"></canvas>
            </div>
          </div>
        </el-col>

        <!-- 3D地球网络流量图 -->
        <el-col :span="12">
          <div class="chart-card starry-background">
            <div class="chart-header">
              <h3>
                <i class="fa fa-wifi"></i>
                网络流量监控
              </h3>
              <div class="network-info">
                <span class="upload">
                  <i class="fa fa-arrow-up"></i>
                  上传: {{ networkStats.upload }}
                </span>
                <span class="download">
                  <i class="fa fa-arrow-down"></i>
                  下载: {{ networkStats.download }}
                </span>
                <span class="total-traffic">
                  <i class="fa fa-exchange"></i>
                  总流量: {{ networkStats.total }}
                </span>
                <span class="location-info">
                  <i class="fa fa-map-marker"></i>
                  位置: {{ networkStats.location || '获取中...' }}
                </span>
                <span class="location-tip" v-if="networkStats.location === '获取中...'">
                  <i class="fa fa-info-circle"></i>
                  请允许浏览器获取位置权限
                </span>
              </div>
            </div>
            <div class="chart-content">
              <div ref="networkGlobeRef" class="network-globe"></div>
            </div>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 主机状态分布 -->
        <el-col :span="8">
          <div class="chart-card starry-background">
            <div class="chart-header">
              <h3>
                <i class="fa fa-server"></i>
                主机状态分布
              </h3>
            </div>
            <div class="chart-content">
              <canvas ref="hostStatusChartRef" class="host-status-chart"></canvas>
              <div class="host-stats">
                <div class="host-stat-item">
                  <div class="status-dot online"></div>
                  <span>在线: {{ hostStats.online }}</span>
                </div>
                <div class="host-stat-item">
                  <div class="status-dot offline"></div>
                  <span>离线: {{ hostStats.offline }}</span>
                </div>
                <div class="host-stat-item">
                  <div class="status-dot warning"></div>
                  <span>告警: {{ hostStats.warning }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 系统信息 -->
        <el-col :span="8">
          <div class="chart-card starry-background">
            <div class="chart-header">
              <h3>
                <i class="fa fa-info-circle"></i>
                系统信息
              </h3>
            </div>
            <div class="chart-content">
              <div class="system-info">
                <div class="info-item">
                  <div class="info-label">操作系统</div>
                  <div class="info-value">{{ systemInfo.os }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">系统版本</div>
                  <div class="info-value">{{ systemInfo.version }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">CPU型号</div>
                  <div class="info-value">{{ systemInfo.cpu }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">总内存</div>
                  <div class="info-value">{{ systemInfo.totalMemory }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">系统启动时间</div>
                  <div class="info-value">{{ systemInfo.uptime }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">负载均衡</div>
                  <div class="info-value">{{ systemInfo.loadAverage }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-col>

        <!-- 最近活动 -->
        <el-col :span="8">
          <div class="chart-card starry-background">
            <div class="chart-header">
              <h3>
                <i class="fa fa-history"></i>
                最近活动
              </h3>
            </div>
            <div class="chart-content">
              <div class="activity-list">
                <div class="activity-item" v-for="(activity, index) in recentActivities" :key="index">
                  <div class="activity-icon" :class="activity.type">
                    <i :class="activity.icon"></i>
                  </div>
                  <div class="activity-content">
                    <div class="activity-title">{{ activity.title }}</div>
                    <div class="activity-desc">{{ activity.description }}</div>
                    <div class="activity-time">{{ activity.time }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from 'axios'
import * as echarts from 'echarts'
import 'echarts-gl'
import { nextTick, onMounted, onUnmounted, ref } from 'vue'

// 创建科技风仪表盘配置
const createCarGaugeOption = (value, title, color) => {
  return {
    backgroundColor: 'transparent',
    series: [
      {
        type: 'gauge',
        center: ['50%', '55%'],
        radius: '75%',
        startAngle: 200,
        endAngle: -40,
        min: 0,
        max: 100,
        splitNumber: 10,
        itemStyle: {
          color: color
        },
        progress: {
          show: true,
          width: 20,
          itemStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 1,
              y2: 0,
              colorStops: [
                { offset: 0, color: color + '40' },
                { offset: 1, color: color }
              ]
            }
          }
        },
        pointer: {
          show: false
        },
        axisLine: {
          lineStyle: {
            width: 20,
            color: [[1, 'rgba(255, 255, 255, 0.1)']]
          }
        },
        axisTick: {
          distance: -30,
          splitNumber: 2,
          lineStyle: {
            width: 1,
            color: 'rgba(255, 255, 255, 0.3)'
          }
        },
        splitLine: {
          distance: -35,
          length: 8,
          lineStyle: {
            width: 2,
            color: 'rgba(255, 255, 255, 0.5)'
          }
        },
        axisLabel: {
          distance: -50,
          color: 'rgba(255, 255, 255, 0.7)',
          fontSize: 12,
          fontWeight: 'bold'
        },
        anchor: {
          show: false
        },
        title: {
          show: true,
          offsetCenter: [0, '80%'],
          fontSize: 14,
          fontWeight: 'bold',
          color: 'rgba(255, 255, 255, 0.8)'
        },
        detail: {
          valueAnimation: true,
          width: '80%',
          lineHeight: 40,
          borderRadius: 8,
          offsetCenter: [0, '10%'],
          fontSize: 28,
          fontWeight: 'bolder',
          formatter: '{value}%',
          color: color,
          backgroundColor: 'rgba(0, 0, 0, 0.5)',
          borderColor: color,
          borderWidth: 1,
          padding: [8, 15],
          overflow: 'hidden'
        },
        data: [
          {
            value: value,
            name: title
          }
        ]
      }
    ]
  }
}

// 响应式数据
const isLoading = ref(true)
const loadingProgress = ref(0)
const lastUpdateTime = ref('')
const timeRange = ref('1h')

// 系统核心指标
const systemMetrics = ref({
  cpu: 0,
  memory: 0,
  disk: 0,
  cpuUsed: '0',
  cpuTotal: '0',
  memoryUsed: '0GB',
  memoryTotal: '0GB',
  diskUsed: '0GB',
  diskTotal: '0GB'
})

// 业务统计数据 - 10个指标，两行各5个
const businessStats = ref([
  {
    label: '主机总数',
    value: 0,
    icon: 'fa fa-server',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+5.2%'
  },
  {
    label: '在线主机',
    value: 0,
    icon: 'fa fa-check-circle',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+2.1%'
  },
  {
    label: '离线主机',
    value: 0,
    icon: 'fa fa-times-circle',
    trend: 'down',
    trendIcon: 'fa fa-arrow-down',
    trendText: '-8.3%'
  },
  {
    label: '告警数量',
    value: 0,
    icon: 'fa fa-exclamation-triangle',
    trend: 'down',
    trendIcon: 'fa fa-arrow-down',
    trendText: '-12.3%'
  },
  {
    label: '本月连接',
    value: 0,
    icon: 'fa fa-plug',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+8.7%'
  },
  {
    label: 'CPU负载',
    value: '0.0',
    icon: 'fa fa-microchip',
    trend: 'stable',
    trendIcon: 'fa fa-minus',
    trendText: '稳定'
  },
  {
    label: '内存使用',
    value: '0GB',
    icon: 'fa fa-memory',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+3.2%'
  },
  {
    label: '磁盘使用',
    value: '0GB',
    icon: 'fa fa-hdd',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+1.8%'
  },
  {
    label: '网络流量',
    value: '0MB/s',
    icon: 'fa fa-wifi',
    trend: 'up',
    trendIcon: 'fa fa-arrow-up',
    trendText: '+15.6%'
  },
  {
    label: '系统进程',
    value: 0,
    icon: 'fa fa-cogs',
    trend: 'stable',
    trendIcon: 'fa fa-minus',
    trendText: '稳定'
  }
])

// 网络统计
const networkStats = ref({
  upload: '125.6 MB/s',
  download: '89.3 MB/s',
  total: '214.9 MB/s',
  location: '获取中...'
})

// 主机状态统计
const hostStats = ref({
  online: 0,
  offline: 0,
  warning: 0
})

// 系统信息
const systemInfo = ref({
  os: 'CentOS 7.9',
  version: 'Linux 3.10.0',
  cpu: 'Intel Xeon E5-2680 v4',
  totalMemory: '32GB',
  uptime: '15天 8小时',
  loadAverage: '1.2, 1.5, 1.8'
})

// 最近活动
const recentActivities = ref([
  {
    type: 'success',
    icon: 'fa fa-user-plus',
    title: '新用户注册',
    description: '用户 admin 成功登录系统',
    time: '2分钟前'
  },
  {
    type: 'warning',
    icon: 'fa fa-exclamation-triangle',
    title: 'CPU使用率告警',
    description: '服务器 web-01 CPU使用率超过80%',
    time: '5分钟前'
  },
  {
    type: 'info',
    icon: 'fa fa-server',
    title: '主机上线',
    description: '主机 db-02 重新上线',
    time: '10分钟前'
  },
  {
    type: 'error',
    icon: 'fa fa-times-circle',
    title: '连接失败',
    description: '主机 cache-01 连接超时',
    time: '15分钟前'
  }
])

// ECharts引用
const cpuGaugeRef = ref()
const memoryGaugeRef = ref()
const diskGaugeRef = ref()
const performanceChartRef = ref()
const networkGlobeRef = ref()
const hostStatusChartRef = ref()
const statChartRefs = ref([])

// ECharts图表实例
let cpuGauge = null
let memoryGauge = null
let diskGauge = null
let performanceChart = null
let networkGlobe = null
let hostStatusChart = null
let statCharts = []

// 全局地球配置缓存
let globeBaseConfig = null
let currentHostLocation = null

// 工具函数
const getStatusClass = (value: number) => {
  if (value < 60) return 'normal'
  if (value < 80) return 'warning'
  return 'danger'
}

const getStatusText = (value: number) => {
  if (value < 60) return '正常'
  if (value < 80) return '警告'
  return '危险'
}

const setTimeRange = (range: string) => {
  timeRange.value = range
  updatePerformanceChart()
}

// 旧的Canvas仪表盘绘制函数已删除，现在使用ECharts汽车仪表盘

// 旧的Canvas仪表盘函数已删除，现在使用ECharts

// 更新性能图表
const updatePerformanceChart = () => {
  if (!performanceChartRef.value) return

  const ctx = performanceChartRef.value.getContext('2d')
  const canvas = performanceChartRef.value

  // 模拟数据
  const timeLabels = []
  const cpuData = []
  const memoryData = []
  const diskData = []

  const now = new Date()
  const points = timeRange.value === '1h' ? 12 : timeRange.value === '6h' ? 24 : 48
  const interval = timeRange.value === '1h' ? 5 : timeRange.value === '6h' ? 15 : 30

  for (let i = points - 1; i >= 0; i--) {
    const time = new Date(now.getTime() - i * interval * 60000)
    timeLabels.push(time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }))

    cpuData.push(Math.random() * 40 + 20 + Math.sin(i * 0.1) * 10)
    memoryData.push(Math.random() * 30 + 40 + Math.cos(i * 0.15) * 8)
    diskData.push(Math.random() * 20 + 30 + Math.sin(i * 0.08) * 5)
  }

  // 绘制图表
  drawLineChart(ctx, canvas, {
    labels: timeLabels,
    datasets: [
      { label: 'CPU', data: cpuData, color: '#3b82f6' },
      { label: '内存', data: memoryData, color: '#10b981' },
      { label: '磁盘', data: diskData, color: '#f59e0b' }
    ]
  })
}

// 绘制折线图
const drawLineChart = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, data: any) => {
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  const padding = 40
  const chartWidth = canvas.width - padding * 2
  const chartHeight = canvas.height - padding * 2

  // 绘制网格
  ctx.strokeStyle = 'rgba(0, 234, 255, 0.1)'
  ctx.lineWidth = 1

  for (let i = 0; i <= 10; i++) {
    const y = padding + (chartHeight / 10) * i
    ctx.beginPath()
    ctx.moveTo(padding, y)
    ctx.lineTo(canvas.width - padding, y)
    ctx.stroke()
  }

  for (let i = 0; i <= data.labels.length - 1; i++) {
    const x = padding + (chartWidth / (data.labels.length - 1)) * i
    ctx.beginPath()
    ctx.moveTo(x, padding)
    ctx.lineTo(x, canvas.height - padding)
    ctx.stroke()
  }

  // 绘制数据线
  data.datasets.forEach((dataset: any) => {
    ctx.strokeStyle = dataset.color
    ctx.lineWidth = 3
    ctx.beginPath()

    dataset.data.forEach((value: number, index: number) => {
      const x = padding + (chartWidth / (data.labels.length - 1)) * index
      const y = canvas.height - padding - (value / 100) * chartHeight

      if (index === 0) {
        ctx.moveTo(x, y)
      } else {
        ctx.lineTo(x, y)
      }
    })

    // 添加发光效果
    ctx.shadowColor = dataset.color
    ctx.shadowBlur = 10
    ctx.stroke()
    ctx.shadowBlur = 0

    // 绘制数据点
    dataset.data.forEach((value: number, index: number) => {
      const x = padding + (chartWidth / (data.labels.length - 1)) * index
      const y = canvas.height - padding - (value / 100) * chartHeight

      ctx.beginPath()
      ctx.arc(x, y, 4, 0, 2 * Math.PI)
      ctx.fillStyle = dataset.color
      ctx.fill()

      // 数据点发光
      ctx.shadowColor = dataset.color
      ctx.shadowBlur = 8
      ctx.beginPath()
      ctx.arc(x, y, 2, 0, 2 * Math.PI)
      ctx.fillStyle = '#ffffff'
      ctx.fill()
      ctx.shadowBlur = 0
    })
  })
}

// 绘制饼图
const drawPieChart = (ctx: CanvasRenderingContext2D, canvas: HTMLCanvasElement, data: any) => {
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  const centerX = canvas.width / 2
  const centerY = canvas.height / 2
  const radius = Math.min(centerX, centerY) - 20

  const total = data.reduce((sum: number, item: any) => sum + item.value, 0)
  let currentAngle = -Math.PI / 2

  data.forEach((item: any, index: number) => {
    const sliceAngle = (item.value / total) * 2 * Math.PI

    // 绘制扇形
    ctx.beginPath()
    ctx.moveTo(centerX, centerY)
    ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle)
    ctx.closePath()

    // 渐变填充
    const gradient = ctx.createRadialGradient(centerX, centerY, 0, centerX, centerY, radius)
    gradient.addColorStop(0, item.color)
    gradient.addColorStop(1, item.color + '80')
    ctx.fillStyle = gradient
    ctx.fill()

    // 边框
    ctx.strokeStyle = item.color
    ctx.lineWidth = 2
    ctx.stroke()

    // 发光效果
    ctx.shadowColor = item.color
    ctx.shadowBlur = 15
    ctx.fill()
    ctx.shadowBlur = 0

    // 绘制标签
    const labelAngle = currentAngle + sliceAngle / 2
    const labelX = centerX + Math.cos(labelAngle) * (radius * 0.7)
    const labelY = centerY + Math.sin(labelAngle) * (radius * 0.7)

    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 14px Arial'
    ctx.textAlign = 'center'
    ctx.textBaseline = 'middle'
    ctx.fillText(item.value.toString(), labelX, labelY)

    currentAngle += sliceAngle
  })

  // 绘制中心圆
  ctx.beginPath()
  ctx.arc(centerX, centerY, radius * 0.4, 0, 2 * Math.PI)
  ctx.fillStyle = 'rgba(15, 23, 42, 0.9)'
  ctx.fill()
  ctx.strokeStyle = 'rgba(0, 234, 255, 0.5)'
  ctx.lineWidth = 2
  ctx.stroke()
}

// 本地获取地理位置（使用浏览器Geolocation API）
const getRealLocation = async () => {
  console.log('开始获取本地地理位置...')

  return new Promise((resolve) => {
    // 检查浏览器是否支持地理位置
    if (!navigator.geolocation) {
      console.log('浏览器不支持地理位置API，使用默认位置')
      resolve(getDefaultLocation())
      return
    }

    // 使用浏览器地理位置API
    navigator.geolocation.getCurrentPosition(
      (position) => {
        const { latitude, longitude } = position.coords
        console.log('获取到真实位置:', { latitude, longitude })

        // 根据坐标判断城市（简单的范围判断）
        const locationInfo = getCityFromCoordinates(latitude, longitude)

        const realLocation = {
          name: locationInfo.name,
          coord: [longitude, latitude], // [经度, 纬度]
          country: locationInfo.country,
          city: locationInfo.city,
          region: locationInfo.region,
          timezone: locationInfo.timezone,
          ip: '本地获取',
          accuracy: position.coords.accuracy
        }

        console.log('解析后的位置信息:', realLocation)
        resolve(realLocation)
      },
      (error) => {
        console.log('地理位置获取失败:', error.message)
        console.log('使用默认位置')
        resolve(getDefaultLocation())
      },
      {
        enableHighAccuracy: true,
        timeout: 10000,
        maximumAge: 300000 // 5分钟缓存
      }
    )
  })
}

// 根据坐标判断城市
const getCityFromCoordinates = (lat, lon) => {
  // 中国主要城市坐标范围
  const cities = [
    {
      name: '上海, 中国',
      city: '上海',
      country: 'CN',
      region: '上海市',
      timezone: 'Asia/Shanghai',
      bounds: { minLat: 30.8, maxLat: 31.5, minLon: 121.0, maxLon: 122.0 }
    },
    {
      name: '北京, 中国',
      city: '北京',
      country: 'CN',
      region: '北京市',
      timezone: 'Asia/Shanghai',
      bounds: { minLat: 39.5, maxLat: 40.5, minLon: 116.0, maxLon: 117.0 }
    },
    {
      name: '广州, 中国',
      city: '广州',
      country: 'CN',
      region: '广东省',
      timezone: 'Asia/Shanghai',
      bounds: { minLat: 22.8, maxLat: 23.5, minLon: 113.0, maxLon: 113.8 }
    },
    {
      name: '深圳, 中国',
      city: '深圳',
      country: 'CN',
      region: '广东省',
      timezone: 'Asia/Shanghai',
      bounds: { minLat: 22.4, maxLat: 22.8, minLon: 113.8, maxLon: 114.5 }
    },
    {
      name: '杭州, 中国',
      city: '杭州',
      country: 'CN',
      region: '浙江省',
      timezone: 'Asia/Shanghai',
      bounds: { minLat: 30.0, maxLat: 30.5, minLon: 119.8, maxLon: 120.5 }
    }
  ]

  // 检查是否在已知城市范围内
  for (const city of cities) {
    const { bounds } = city
    if (lat >= bounds.minLat && lat <= bounds.maxLat &&
        lon >= bounds.minLon && lon <= bounds.maxLon) {
      console.log('匹配到城市:', city.name)
      return city
    }
  }

  // 如果不在已知范围内，根据大致区域判断
  if (lat >= 18 && lat <= 54 && lon >= 73 && lon <= 135) {
    return {
      name: '中国某地',
      city: '未知城市',
      country: 'CN',
      region: '中国',
      timezone: 'Asia/Shanghai'
    }
  }

  // 默认返回全球位置
  return {
    name: `位置 (${lat.toFixed(2)}, ${lon.toFixed(2)})`,
    city: '未知',
    country: 'Unknown',
    region: '未知',
    timezone: 'UTC'
  }
}

// 获取默认位置
const getDefaultLocation = () => {
  return {
    name: '上海, 中国',
    coord: [121.4737, 31.2304],
    country: 'CN',
    city: '上海',
    region: '上海市',
    timezone: 'Asia/Shanghai',
    ip: '默认位置'
  }
}

// 优化的ECharts仪表盘更新
const updateGauges = () => {
  console.log('开始更新仪表盘...')

  // 更新CPU仪表盘
  if (cpuGaugeRef.value) {
    console.log('CPU仪表盘DOM存在，开始初始化...')
    if (!cpuGauge) {
      cpuGauge = echarts.init(cpuGaugeRef.value, null, {
        renderer: 'canvas',
        useDirtyRect: true // 启用脏矩形优化
      })
      console.log('CPU仪表盘实例创建成功')
    }
    const cpuOption = createCarGaugeOption(systemMetrics.value.cpu, 'CPU使用率', '#00eaff')
    cpuGauge.setOption(cpuOption, { notMerge: false, lazyUpdate: false })
  }

  // 更新内存仪表盘
  if (memoryGaugeRef.value) {
    console.log('内存仪表盘DOM存在，开始初始化...')
    if (!memoryGauge) {
      memoryGauge = echarts.init(memoryGaugeRef.value, null, {
        renderer: 'canvas',
        useDirtyRect: true
      })
      console.log('内存仪表盘实例创建成功')
    }
    const memoryOption = createCarGaugeOption(systemMetrics.value.memory, '内存使用率', '#10b981')
    memoryGauge.setOption(memoryOption, { notMerge: false, lazyUpdate: false })
  }

  // 更新磁盘仪表盘
  if (diskGaugeRef.value) {
    console.log('磁盘仪表盘DOM存在，开始初始化...')
    if (!diskGauge) {
      diskGauge = echarts.init(diskGaugeRef.value, null, {
        renderer: 'canvas',
        useDirtyRect: true
      })
      console.log('磁盘仪表盘实例创建成功')
    }
    const diskOption = createCarGaugeOption(systemMetrics.value.disk, '磁盘使用率', '#f59e0b')
    diskGauge.setOption(diskOption, { notMerge: false, lazyUpdate: false })
  }
}

// 创建3D地球网络流量图
const createNetworkGlobe = async () => {
  console.log('开始创建3D地球...')

  if (!networkGlobeRef.value) {
    console.log('3D地球DOM不存在')
    return
  }

  console.log('3D地球DOM存在，开始初始化...')

  // 销毁现有实例
  if (networkGlobe) {
    networkGlobe.dispose()
    networkGlobe = null
    console.log('销毁旧的3D地球实例')
  }

  // 创建新的ECharts实例
  try {
    networkGlobe = echarts.init(networkGlobeRef.value)
    console.log('3D地球ECharts实例创建成功')
  } catch (error) {
    console.error('创建3D地球ECharts实例失败:', error)
    return
  }

  // 使用本地资源，不需要加载外部地图数据

  // 获取真实的地理位置
  const hostLocation = await getRealLocation()
  console.log('当前位置:', hostLocation)

  // 保存当前位置
  currentHostLocation = hostLocation

  console.log('使用本地资源创建Hello World地球')

  // 简化的3D地球配置，确保能正常显示
  const option = {
    backgroundColor: 'transparent',
    globe: {
      baseTexture: '/assets/globe/world.topo.bathy.200401.jpg',
      shading: 'lambert',
      environment: '/assets/globe/starfield.jpg',
      atmosphere: {
        show: true,
        offset: 5,
        color: '#87CEEB',
        glowPower: 6,
        innerGlowPower: 2
      },
      viewControl: {
        autoRotate: true,
        autoRotateSpeed: 1,
        distance: 200,
        minDistance: 150,
        maxDistance: 400
      },
      light: {
        main: {
          intensity: 2,
          shadow: false
        }
      }
    },
    series: [
      {
        type: 'scatter3D',
        coordinateSystem: 'globe',
        symbolSize: 15,
        itemStyle: {
          color: '#ff4757',
          opacity: 1
        },
        label: {
          show: true,
          position: 'top',
          formatter: function(params) {
            return params.data.name
          },
          color: '#ffffff',
          fontSize: 12,
          fontWeight: 'bold',
          borderColor: '#000',
          borderWidth: 1
        },
        data: [{
          name: hostLocation.name,
          value: [...hostLocation.coord, 100]
        }]
      }
    ]
  }

  console.log('设置Hello World地球配置:', option)
  console.log('数据点坐标:', hostLocation.coord)

  // 保存配置供更新使用
  globeBaseConfig = option

  // 确保networkGlobe实例存在
  if (!networkGlobe) {
    console.error('networkGlobe实例不存在，无法设置配置')
    return
  }

  try {
    networkGlobe.setOption(option)
  } catch (error) {
    console.error('设置3D地球配置失败:', error)
    return
  }

  // 更新位置信息显示
  networkStats.value.location = hostLocation.name

  // 响应式调整
  const resizeObserver = new ResizeObserver(() => {
    networkGlobe?.resize()
  })
  resizeObserver.observe(networkGlobeRef.value)

  return resizeObserver
}

const fetchDashboardData = async () => {
  try {
    // 获取系统指标
    const response = await axios.get('/api/system-metrics/')
    const data = response.data

    // 更新业务统计
    if (data) {
      businessStats.value[0].value = data.total_hosts || 0
      businessStats.value[1].value = data.online_hosts || 0
      businessStats.value[2].value = (data.total_hosts || 0) - (data.online_hosts || 0) // 离线主机
      businessStats.value[3].value = data.alert_count || 0
      businessStats.value[4].value = data.monthly_connections || 0

      // 更新主机状态统计
      hostStats.value.online = data.online_hosts || 0
      hostStats.value.offline = (data.total_hosts || 0) - (data.online_hosts || 0)
      hostStats.value.warning = data.alert_count || 0
    }

    // 更新系统指标 - 直接从data中获取，不是从system_metrics
    // CPU指标
    systemMetrics.value.cpu = Math.round(data.cpu_usage || 0)
    systemMetrics.value.cpuUsed = Math.round((data.cpu_usage || 0) * (data.cpu_count || 1) / 100).toString()
    systemMetrics.value.cpuTotal = (data.cpu_count || 0).toString()

    // 内存指标
    systemMetrics.value.memory = Math.round(data.memory_usage || 0)
    systemMetrics.value.memoryUsed = formatBytes(data.memory_used || 0)
    systemMetrics.value.memoryTotal = formatBytes(data.memory_total || 0)

    // 磁盘指标
    systemMetrics.value.disk = Math.round(data.disk_usage || 0)
    systemMetrics.value.diskUsed = formatBytes(data.disk_used || 0)
    systemMetrics.value.diskTotal = formatBytes(data.disk_total || 0)

    // 计算CPU负载（基于CPU使用率）
    const cpuLoad = ((data.cpu_usage || 0) / 100 * (data.cpu_count || 1)).toFixed(1)

    // 计算网络总流量（上传+下载）
    const totalNetworkBytes = (data.network?.bytes_sent || 0) + (data.network?.bytes_recv || 0)

    // 估算系统进程数（基于CPU核心数和负载）
    const estimatedProcesses = Math.round((data.cpu_count || 1) * 20 + (data.cpu_usage || 0) * 2)

    // 更新业务统计中的系统指标
    businessStats.value[5].value = cpuLoad // CPU负载
    businessStats.value[6].value = formatBytes(data.memory_used || 0) // 内存使用
    businessStats.value[7].value = formatBytes(data.disk_used || 0) // 磁盘使用
    businessStats.value[8].value = formatBytes(totalNetworkBytes) // 网络流量总计
    businessStats.value[9].value = estimatedProcesses // 系统进程

    // 更新网络统计（转换为速度显示）
    const uploadSpeed = data.network?.bytes_sent || 0
    const downloadSpeed = data.network?.bytes_recv || 0
    const totalSpeed = uploadSpeed + downloadSpeed

    networkStats.value.upload = formatBytes(uploadSpeed) + '/s'
    networkStats.value.download = formatBytes(downloadSpeed) + '/s'
    networkStats.value.total = formatBytes(totalSpeed) + '/s'

    // 更新系统信息 - 使用默认值或从其他地方获取
    systemInfo.value.os = 'Linux'
    systemInfo.value.version = 'Unknown'
    systemInfo.value.cpu = `${data.cpu_count || 0}核 CPU`
    systemInfo.value.totalMemory = formatBytes(data.memory_total || 0)
    systemInfo.value.uptime = 'Unknown'
    systemInfo.value.loadAverage = '0.0, 0.0, 0.0'

    // 更新时间
    lastUpdateTime.value = new Date().toLocaleString('zh-CN')

    // 只在非加载状态时更新图表
    if (!isLoading.value) {
      nextTick(() => {
        updateGauges()
        updatePerformanceChart()
        updateHostStatusChart()
        updateNetworkGlobe()
      })
    }

  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
  }
}

// 更新主机状态图表
const updateHostStatusChart = () => {
  if (!hostStatusChartRef.value) return

  const ctx = hostStatusChartRef.value.getContext('2d')
  const data = [
    { label: '在线', value: hostStats.value.online, color: '#10b981' },
    { label: '离线', value: hostStats.value.offline, color: '#ef4444' },
    { label: '告警', value: hostStats.value.warning, color: '#f59e0b' }
  ]

  drawPieChart(ctx, hostStatusChartRef.value, data)
}

// 更新网络地球图表
const updateNetworkGlobe = () => {
  if (!networkGlobe || !currentHostLocation) {
    console.log('地球实例或位置不存在，跳过更新')
    return
  }

  console.log('更新网络地球数据...')

  // 只更新数据点的值
  const updatedValue = Math.random() * 100 + 50

  networkGlobe.setOption({
    series: [{
      data: [{
        name: currentHostLocation.name,
        value: [...currentHostLocation.coord, updatedValue]
      }]
    }]
  })
}

// 格式化字节数
const formatBytes = (bytes: number): string => {
  if (bytes === 0) return '0B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + sizes[i]
}

// 格式化网络速度
const formatNetworkSpeed = (bytesPerSecond: number): string => {
  if (bytesPerSecond === 0) return '0B/s'
  const k = 1024
  const sizes = ['B/s', 'KB/s', 'MB/s', 'GB/s']
  const i = Math.floor(Math.log(bytesPerSecond) / Math.log(k))
  return parseFloat((bytesPerSecond / Math.pow(k, i)).toFixed(1)) + sizes[i]
}

// 格式化运行时间
const formatUptime = (seconds: number): string => {
  const days = Math.floor(seconds / 86400)
  const hours = Math.floor((seconds % 86400) / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)

  if (days > 0) {
    return `${days}天 ${hours}小时`
  } else if (hours > 0) {
    return `${hours}小时 ${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 优化的基础图表初始化
const initBasicCharts = async () => {
  await nextTick()

  // 设置Canvas图表尺寸
  if (performanceChartRef.value) {
    performanceChartRef.value.width = 600
    performanceChartRef.value.height = 320
  }
  if (hostStatusChartRef.value) {
    hostStatusChartRef.value.width = 200
    hostStatusChartRef.value.height = 200
  }
}

// 保留原有的初始化函数用于数据刷新时使用
const initCharts = () => {
  nextTick(() => {
    updateGauges()
    updatePerformanceChart()
    updateHostStatusChart()
  })
}

let refreshTimer: any = null

// 分步加载函数
const loadDashboardStep = async (step: number, total: number) => {
  loadingProgress.value = Math.round((step / total) * 100)
  await new Promise(resolve => setTimeout(resolve, 50)) // 短暂延迟让UI更新
}

// 优化的初始化流程
const initializeDashboard = async () => {
  try {
    isLoading.value = true
    loadingProgress.value = 0

    // 等待DOM渲染完成
    await nextTick()

    // 步骤1: 获取基础数据
    await loadDashboardStep(1, 6)
    await fetchDashboardData()

    // 步骤2: 初始化基础图表容器
    await loadDashboardStep(2, 6)
    await initBasicCharts()

    // 步骤3: 渲染仪表盘
    await loadDashboardStep(3, 6)
    await nextTick()
    updateGauges()

    // 步骤4: 渲染性能图表
    await loadDashboardStep(4, 6)
    await nextTick()
    updatePerformanceChart()
    updateHostStatusChart()

    // 步骤5: 初始化3D地球（最耗性能的放最后）
    await loadDashboardStep(5, 6)
    await nextTick()
    createNetworkGlobe().catch(console.error)

    // 步骤6: 完成
    await loadDashboardStep(6, 6)
    await new Promise(resolve => setTimeout(resolve, 200)) // 让用户看到100%

    isLoading.value = false

    // 启动定时刷新
    refreshTimer = setInterval(() => {
      fetchDashboardData()
    }, 10000)

  } catch (error) {
    console.error('仪表盘初始化失败:', error)
    isLoading.value = false
  }
}

onMounted(() => {
  initializeDashboard()
})

onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }

  // 清理所有ECharts实例
  if (cpuGauge) {
    cpuGauge.dispose()
    cpuGauge = null
  }
  if (memoryGauge) {
    memoryGauge.dispose()
    memoryGauge = null
  }
  if (diskGauge) {
    diskGauge.dispose()
    diskGauge = null
  }
  if (networkGlobe) {
    networkGlobe.dispose()
    networkGlobe = null
  }
})
</script>

<style lang="scss" scoped>
.tech-dashboard {
  min-height: 100vh;
  background:
    radial-gradient(circle at 20% 80%, rgba(0, 234, 255, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 80% 20%, rgba(59, 130, 246, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 40% 40%, rgba(139, 92, 246, 0.05) 0%, transparent 50%),
    linear-gradient(135deg, #0a0e1a 0%, #1a1f2e 25%, #0f1327 50%, #1a2332 75%, #0f1327 100%);
  color: #e6e6e6;
  padding: 20px 20px 100px 20px;
  position: relative;
  overflow-x: hidden;

  // 加载状态
  .dashboard-loading {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background:
      radial-gradient(circle at 20% 80%, rgba(139, 92, 246, 0.15) 0%, transparent 50%),
      radial-gradient(circle at 80% 20%, rgba(0, 234, 255, 0.15) 0%, transparent 50%),
      radial-gradient(circle at 40% 40%, rgba(236, 72, 153, 0.1) 0%, transparent 50%),
      linear-gradient(135deg, #0a0e1a 0%, #1a1f2e 25%, #0f1327 50%, #1a2332 75%, #0f1327 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    overflow: hidden;

    &::before {
      content: '';
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background:
        radial-gradient(circle, rgba(0, 234, 255, 0.03) 1px, transparent 1px);
      background-size: 50px 50px;
      animation: float 20s ease-in-out infinite;
      pointer-events: none;
    }

    .loading-content {
      text-align: center;
      padding: 60px 50px;
      border-radius: 25px;
      background:
        linear-gradient(145deg, rgba(0, 0, 0, 0.4), rgba(20, 20, 40, 0.3));
      border: 2px solid transparent;
      background-clip: padding-box;
      backdrop-filter: blur(20px);
      box-shadow:
        0 20px 60px rgba(0, 0, 0, 0.5),
        inset 0 1px 0 rgba(255, 255, 255, 0.1),
        0 0 0 1px rgba(0, 234, 255, 0.2);
      position: relative;
      overflow: hidden;

      &::before {
        content: '';
        position: absolute;
        top: -2px;
        left: -2px;
        right: -2px;
        bottom: -2px;
        background: linear-gradient(45deg, #00eaff, #8b5cf6, #ec4899, #00eaff);
        background-size: 400% 400%;
        border-radius: 25px;
        z-index: -1;
        animation: gradientRotate 3s ease-in-out infinite;
      }

      .loading-spinner-container {
        margin-bottom: 30px;

        .loading-spinner {
          position: relative;
          width: 120px;
          height: 120px;
          margin: 0 auto;

          .spinner-ring {
            position: absolute;
            border: 3px solid transparent;
            border-radius: 50%;

            &:nth-child(1) {
              width: 120px;
              height: 120px;
              border-top: 3px solid #00eaff;
              border-right: 3px solid #00eaff;
              animation: spinRing1 2s linear infinite;
              box-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
            }

            &:nth-child(2) {
              width: 90px;
              height: 90px;
              top: 15px;
              left: 15px;
              border-bottom: 3px solid #8b5cf6;
              border-left: 3px solid #8b5cf6;
              animation: spinRing2 1.5s linear infinite reverse;
              box-shadow: 0 0 15px rgba(139, 92, 246, 0.5);
            }

            &:nth-child(3) {
              width: 60px;
              height: 60px;
              top: 30px;
              left: 30px;
              border-top: 3px solid #ec4899;
              border-right: 3px solid #ec4899;
              animation: spinRing3 1s linear infinite;
              box-shadow: 0 0 10px rgba(236, 72, 153, 0.5);
            }
          }

          .spinner-core {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 32px;
            color: #ffffff;
            animation: pulse 2s ease-in-out infinite;
            text-shadow: 0 0 20px rgba(255, 255, 255, 0.8);

            i {
              animation: rocketBounce 1.5s ease-in-out infinite;
            }
          }
        }
      }

      .loading-text {
        font-size: 24px;
        margin-bottom: 30px;
        font-weight: 700;

        .text-glow {
          color: #ffffff;
          text-shadow:
            0 0 10px rgba(0, 234, 255, 0.8),
            0 0 20px rgba(0, 234, 255, 0.6),
            0 0 30px rgba(0, 234, 255, 0.4),
            0 2px 4px rgba(0, 0, 0, 0.8);
          animation: textPulse 2s ease-in-out infinite;
          letter-spacing: 1px;
        }

        .dots {
          .dot {
            display: inline-block;
            color: #00eaff;
            font-weight: bold;
            text-shadow: 0 0 15px rgba(0, 234, 255, 0.8);
            animation: dotBounce 1.4s ease-in-out infinite;

            &:nth-child(1) { animation-delay: 0s; }
            &:nth-child(2) { animation-delay: 0.2s; }
            &:nth-child(3) { animation-delay: 0.4s; }
          }
        }
      }

      .loading-progress {
        width: 350px;
        height: 8px;
        background: rgba(0, 0, 0, 0.3);
        border-radius: 10px;
        overflow: hidden;
        margin: 0 auto;
        position: relative;
        border: 1px solid rgba(0, 234, 255, 0.2);

        .progress-bar {
          height: 100%;
          background: linear-gradient(90deg, #00eaff, #8b5cf6, #ec4899);
          border-radius: 10px;
          transition: width 0.5s ease;
          position: relative;
          overflow: hidden;

          .progress-glow {
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
            animation: progressScan 2s ease-in-out infinite;
          }
        }

        .progress-text {
          position: absolute;
          top: -30px;
          right: 0;
          font-size: 14px;
          color: #00eaff;
          font-weight: 600;
          text-shadow: 0 0 10px rgba(0, 234, 255, 0.5);
        }
      }
    }
  }

  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background:
      repeating-linear-gradient(
        90deg,
        transparent,
        transparent 98px,
        rgba(0, 234, 255, 0.03) 100px
      ),
      repeating-linear-gradient(
        0deg,
        transparent,
        transparent 98px,
        rgba(0, 234, 255, 0.03) 100px
      );
    pointer-events: none;
    z-index: 1;
  }

  &::after {
    content: '';
    position: fixed;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background:
      radial-gradient(circle, rgba(0, 234, 255, 0.02) 1px, transparent 1px);
    background-size: 50px 50px;
    animation: float 20s ease-in-out infinite;
    pointer-events: none;
    z-index: 1;
  }

  > * {
    position: relative;
    z-index: 2;
  }

  // 页面标题区域
  .dashboard-header {
    text-align: center;
    margin-bottom: 40px;
    padding: 40px;
    border-radius: 20px;
    border: 1px solid rgba(0, 234, 255, 0.2);
    position: relative;
    overflow: hidden;
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    box-shadow:
      0 8px 32px rgba(0, 0, 0, 0.3),
      inset 0 1px 0 rgba(255, 255, 255, 0.05);

    &::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: radial-gradient(circle at 30% 30%, rgba(0, 234, 255, 0.05) 0%, transparent 50%);
      pointer-events: none;
      z-index: 1;
    }

    &:hover {
      transform: translateY(-5px);
      border-color: rgba(0, 234, 255, 0.4);
      box-shadow:
        0 8px 32px rgba(0, 0, 0, 0.4),
        0 0 20px rgba(0, 234, 255, 0.1),
        inset 0 1px 0 rgba(255, 255, 255, 0.1);
    }

    .dashboard-title {
      font-size: 42px;
      font-weight: 800;
      background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899);
      background-size: 200% 200%;
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
      margin: 0 0 15px 0;
      text-shadow: 0 0 30px rgba(139, 92, 246, 0.6);
      animation: gradientShift 4s ease-in-out infinite;
      letter-spacing: 2px;

      i {
        margin-right: 20px;
        background: linear-gradient(45deg, #6366f1, #8b5cf6);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        animation: pulse 3s infinite, rotate 15s linear infinite;
        display: inline-block;
      }
    }

    .dashboard-subtitle {
      font-size: 16px;
      color: #8892b0;
      margin-bottom: 15px;
      letter-spacing: 1px;
    }

    .last-update {
      font-size: 14px;
      color: #64748b;

      i {
        margin-right: 8px;
        color: #00eaff;
      }
    }
  }

  // 区域标题
  .section-title {
    font-size: 24px;
    font-weight: 600;
    color: #00eaff;
    margin-bottom: 25px;
    padding: 15px 0;
    border-bottom: 2px solid rgba(0, 234, 255, 0.3);
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.4);

    i {
      margin-right: 12px;
      font-size: 20px;
    }
  }

  // 赛车仪表盘区域
  .gauges-section {
    margin-bottom: 40px;

    .gauges-container {
      display: flex;
      justify-content: space-around;
      gap: 30px;
      flex-wrap: wrap;

      .gauge-item {
        flex: 1;
        min-width: 300px;
        max-width: 400px;

        .gauge-wrapper {
          border-radius: 20px;
          padding: 25px;
          border: 1px solid rgba(0, 234, 255, 0.2);
          box-shadow:
            0 8px 32px rgba(0, 0, 0, 0.3),
            inset 0 1px 0 rgba(255, 255, 255, 0.05);
          position: relative;
          overflow: hidden;
          backdrop-filter: blur(10px);
          transition: all 0.3s ease;

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle at 30% 30%, rgba(0, 234, 255, 0.05) 0%, transparent 50%);
            pointer-events: none;
            z-index: 1;
          }

          &:hover {
            transform: translateY(-5px);
            border-color: rgba(0, 234, 255, 0.4);
            box-shadow:
              0 8px 32px rgba(0, 0, 0, 0.4),
              0 0 20px rgba(0, 234, 255, 0.1),
              inset 0 1px 0 rgba(255, 255, 255, 0.1);
          }

          .gauge-chart {
            width: 100%;
            height: 200px;
            margin: 0 auto 10px;
          }

          .gauge-info {
            text-align: center;

            .gauge-label {
              font-size: 18px;
              font-weight: 600;
              color: #00eaff;
              margin-bottom: 10px;
              text-transform: uppercase;
              letter-spacing: 1px;
            }

            .gauge-value {
              font-size: 32px;
              font-weight: 700;
              color: #ffffff;
              margin-bottom: 12px;
              text-shadow: 0 0 15px rgba(255, 255, 255, 0.5);
            }

            .gauge-details {
              display: flex;
              justify-content: space-between;
              margin-bottom: 12px;
              padding: 8px 12px;
              background: rgba(0, 234, 255, 0.1);
              border-radius: 8px;
              border: 1px solid rgba(0, 234, 255, 0.2);

              .detail-item {
                display: flex;
                flex-direction: column;
                align-items: center;

                .detail-label {
                  font-size: 11px;
                  color: #8892b0;
                  margin-bottom: 2px;
                }

                .detail-value {
                  font-size: 13px;
                  font-weight: 600;
                  color: #00eaff;
                }
              }
            }

            .gauge-status {
              font-size: 14px;
              font-weight: 500;
              padding: 4px 12px;
              border-radius: 20px;
              text-transform: uppercase;
              letter-spacing: 0.5px;

              &.normal {
                background: rgba(16, 185, 129, 0.2);
                color: #10b981;
                border: 1px solid rgba(16, 185, 129, 0.3);
              }

              &.warning {
                background: rgba(245, 158, 11, 0.2);
                color: #f59e0b;
                border: 1px solid rgba(245, 158, 11, 0.3);
              }

              &.danger {
                background: rgba(239, 68, 68, 0.2);
                color: #ef4444;
                border: 1px solid rgba(239, 68, 68, 0.3);
              }
            }
          }
        }
      }
    }
  }

  // 统计卡片区域
  .stats-section {
    margin-bottom: 40px;

    .stats-grid {
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      gap: 20px;

      .stat-card {
        border-radius: 15px;
        padding: 25px;
        border: 1px solid rgba(0, 234, 255, 0.2);
        display: flex;
        align-items: center;
        gap: 20px;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
        backdrop-filter: blur(10px);
        box-shadow:
          0 8px 32px rgba(0, 0, 0, 0.3),
          inset 0 1px 0 rgba(255, 255, 255, 0.05);

        &::before {
          content: '';
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: radial-gradient(circle at 30% 30%, rgba(0, 234, 255, 0.05) 0%, transparent 50%);
          pointer-events: none;
          z-index: 1;
        }

        &:hover {
          transform: translateY(-5px);
          border-color: rgba(0, 234, 255, 0.4);
          box-shadow:
            0 8px 32px rgba(0, 0, 0, 0.4),
            0 0 20px rgba(0, 234, 255, 0.1),
            inset 0 1px 0 rgba(255, 255, 255, 0.1);
        }

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          background: linear-gradient(135deg, rgba(0, 234, 255, 0.2), rgba(0, 234, 255, 0.1));
          display: flex;
          align-items: center;
          justify-content: center;

          i {
            font-size: 24px;
            color: #00eaff;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: 700;
            color: #ffffff;
            margin-bottom: 5px;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.3);
          }

          .stat-label {
            font-size: 14px;
            color: #8892b0;
            margin-bottom: 8px;
          }

          .stat-trend {
            font-size: 12px;
            font-weight: 500;

            &.up {
              color: #10b981;
            }

            &.down {
              color: #ef4444;
            }

            &.stable {
              color: #6b7280;
            }

            i {
              margin-right: 4px;
            }
          }
        }

        .stat-chart {
          width: 80px;
          height: 40px;

          .mini-chart {
            width: 100%;
            height: 100%;
          }
        }
      }
    }
  }

  // 图表区域
  .charts-section {
    .chart-card {
      border-radius: 20px;
      border: 1px solid rgba(0, 234, 255, 0.2);
      overflow: hidden;
      margin-bottom: 20px;
      backdrop-filter: blur(10px);
      box-shadow:
        0 8px 32px rgba(0, 0, 0, 0.3),
        inset 0 1px 0 rgba(255, 255, 255, 0.05);
      transition: all 0.3s ease;
      position: relative;

      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: radial-gradient(circle at 30% 30%, rgba(0, 234, 255, 0.05) 0%, transparent 50%);
        pointer-events: none;
        z-index: 1;
      }

      &:hover {
        transform: translateY(-5px);
        border-color: rgba(0, 234, 255, 0.4);
        box-shadow:
          0 8px 32px rgba(0, 0, 0, 0.4),
          0 0 20px rgba(0, 234, 255, 0.1),
          inset 0 1px 0 rgba(255, 255, 255, 0.1);
      }

      .chart-header {
        padding: 20px 25px;
        border-bottom: 1px solid rgba(0, 234, 255, 0.2);
        display: flex;
        justify-content: space-between;
        align-items: center;

        h3 {
          margin: 0;
          font-size: 16px;
          font-weight: 500;
          color: #00eaff;

          i {
            margin-right: 8px;
            font-size: 14px;
          }
        }

        .chart-controls {
          .el-button-group .el-button {
            background: rgba(0, 234, 255, 0.1);
            border-color: rgba(0, 234, 255, 0.3);
            color: #8892b0;

            &.el-button--primary {
              background: rgba(0, 234, 255, 0.2);
              color: #00eaff;
            }
          }
        }

        .network-info {
          display: flex;
          gap: 15px;
          flex-wrap: wrap;

          .upload, .download, .total-traffic, .location-info, .location-tip {
            font-size: 13px;
            color: #8892b0;
            padding: 4px 8px;
            border-radius: 4px;
            background: rgba(0, 0, 0, 0.2);

            i {
              margin-right: 5px;
            }

            &.upload i {
              color: #10b981;
            }

            &.download i {
              color: #3b82f6;
            }

            &.total-traffic i {
              color: #00eaff;
            }

            &.location-info i {
              color: #ff6b6b;
            }

            &.location-tip {
              background: rgba(245, 158, 11, 0.2);
              color: #f59e0b;
              font-size: 12px;

              i {
                color: #f59e0b;
              }
            }
          }
        }
      }

      .chart-content {
        padding: 25px;
        min-height: 350px;
        display: flex;
        flex-direction: column;

        .performance-chart,
        .network-chart {
          width: 100%;
          height: 320px;
          display: block;
        }

        .network-globe {
          width: 100%;
          height: 320px;
          border-radius: 8px;
          overflow: hidden;
          background: radial-gradient(circle at center, rgba(0, 15, 30, 0.9) 0%, rgba(0, 0, 0, 0.95) 100%);
          position: relative;

          &::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: radial-gradient(circle at 30% 30%, rgba(0, 234, 255, 0.05) 0%, transparent 50%);
            pointer-events: none;
            z-index: 1;
          }
        }

        .host-status-chart {
          width: 200px;
          height: 200px;
          display: block;
          margin: 0 auto 20px;
        }

        .system-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
        }

        .activity-list {
          height: 280px;
          overflow-y: auto;
          display: flex;
          flex-direction: column;
        }

        .host-stats {
          display: flex;
          justify-content: center;
          gap: 20px;

          .host-stat-item {
            display: flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
            color: #8892b0;

            .status-dot {
              width: 12px;
              height: 12px;
              border-radius: 50%;

              &.online {
                background: #10b981;
                box-shadow: 0 0 8px rgba(16, 185, 129, 0.6);
              }

              &.offline {
                background: #ef4444;
                box-shadow: 0 0 8px rgba(239, 68, 68, 0.6);
              }

              &.warning {
                background: #f59e0b;
                box-shadow: 0 0 8px rgba(245, 158, 11, 0.6);
              }
            }
          }
        }
      }
    }
  }
}

// 星空背景通用样式
.starry-background {
  background:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent),
    radial-gradient(1px 1px at 130px 80px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 160px 30px, rgba(255,255,255,0.9), transparent),
    radial-gradient(1px 1px at 200px 90px, #fff, transparent),
    radial-gradient(1px 1px at 240px 50px, rgba(255,255,255,0.7), transparent),
    radial-gradient(2px 2px at 280px 10px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 320px 70px, #fff, transparent),
    radial-gradient(1px 1px at 360px 40px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 20px 120px, rgba(255,255,255,0.9), transparent),
    radial-gradient(1px 1px at 60px 150px, #fff, transparent),
    radial-gradient(1px 1px at 100px 110px, rgba(255,255,255,0.7), transparent),
    radial-gradient(2px 2px at 140px 160px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 180px 130px, #fff, transparent),
    radial-gradient(1px 1px at 220px 170px, rgba(255,255,255,0.6), transparent),
    radial-gradient(2px 2px at 260px 140px, rgba(255,255,255,0.9), transparent),
    radial-gradient(1px 1px at 300px 180px, #fff, transparent),
    radial-gradient(1px 1px at 340px 150px, rgba(255,255,255,0.7), transparent),
    radial-gradient(2px 2px at 380px 190px, rgba(255,255,255,0.8), transparent),
    radial-gradient(circle at center, rgba(0, 15, 30, 0.9) 0%, rgba(0, 0, 0, 0.95) 100%);
  background-repeat: repeat;
  background-size: 400px 200px;
  animation: sparkle 20s linear infinite;
}

// 动画效果
@keyframes shimmer {
  0% { left: -100%; }
  100% { left: 100%; }
}

@keyframes pulse {
  0%, 100% { transform: scale(1); }
  50% { transform: scale(1.1); }
}

@keyframes scan {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

@keyframes borderGlow {
  0%, 100% {
    background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
  }
  25% {
    background: linear-gradient(45deg, #8b5cf6, #ec4899, #6366f1, #8b5cf6);
  }
  50% {
    background: linear-gradient(45deg, #ec4899, #6366f1, #8b5cf6, #ec4899);
  }
  75% {
    background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
  }
}

@keyframes gradientShift {
  0%, 100% {
    background-position: 0% 50%;
  }
  50% {
    background-position: 100% 50%;
  }
}

@keyframes rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
  }
  33% {
    transform: translate(30px, -30px) rotate(120deg);
  }
  66% {
    transform: translate(-20px, 20px) rotate(240deg);
  }
}

@keyframes glow {
  0%, 100% {
    box-shadow: 0 0 20px rgba(0, 234, 255, 0.3);
  }
  50% {
    box-shadow: 0 0 40px rgba(0, 234, 255, 0.6);
  }
}

@keyframes borderRotate {
  0% {
    background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
  }
  25% {
    background: linear-gradient(45deg, #8b5cf6, #ec4899, #6366f1, #8b5cf6);
  }
  50% {
    background: linear-gradient(45deg, #ec4899, #6366f1, #8b5cf6, #ec4899);
  }
  75% {
    background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
  }
  100% {
    background: linear-gradient(45deg, #6366f1, #8b5cf6, #ec4899, #6366f1);
  }
}

@keyframes scanSlow {
  0% { left: -100%; }
  100% { left: 100%; }
}

@keyframes sparkle {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.8;
  }
}

@keyframes lightning {
  0% {
    box-shadow:
      0 0 40px rgba(139, 92, 246, 0.5),
      0 0 80px rgba(99, 102, 241, 0.3),
      0 25px 50px rgba(0, 0, 0, 0.6);
  }
  25% {
    box-shadow:
      0 0 60px rgba(139, 92, 246, 0.7),
      0 0 120px rgba(99, 102, 241, 0.5),
      0 25px 50px rgba(0, 0, 0, 0.6);
  }
  50% {
    box-shadow:
      0 0 80px rgba(139, 92, 246, 0.9),
      0 0 160px rgba(99, 102, 241, 0.7),
      0 25px 50px rgba(0, 0, 0, 0.6);
  }
  75% {
    box-shadow:
      0 0 60px rgba(139, 92, 246, 0.7),
      0 0 120px rgba(99, 102, 241, 0.5),
      0 25px 50px rgba(0, 0, 0, 0.6);
  }
  100% {
    box-shadow:
      0 0 40px rgba(139, 92, 246, 0.5),
      0 0 80px rgba(99, 102, 241, 0.3),
      0 25px 50px rgba(0, 0, 0, 0.6);
  }
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 新增的炫酷动画
@keyframes textPulse {
  0%, 100% {
    text-shadow:
      0 0 10px rgba(0, 234, 255, 0.8),
      0 0 20px rgba(0, 234, 255, 0.6),
      0 0 30px rgba(0, 234, 255, 0.4),
      0 2px 4px rgba(0, 0, 0, 0.8);
    transform: scale(1);
  }
  50% {
    text-shadow:
      0 0 15px rgba(0, 234, 255, 1),
      0 0 25px rgba(0, 234, 255, 0.8),
      0 0 35px rgba(0, 234, 255, 0.6),
      0 2px 4px rgba(0, 0, 0, 0.8);
    transform: scale(1.02);
  }
}

@keyframes dotBounce {
  0%, 80%, 100% {
    transform: scale(1) translateY(0);
    opacity: 0.7;
  }
  40% {
    transform: scale(1.3) translateY(-8px);
    opacity: 1;
  }
}

// 新增的炫酷动画
@keyframes gradientRotate {
  0% { background-position: 0% 50%; }
  50% { background-position: 100% 50%; }
  100% { background-position: 0% 50%; }
}

@keyframes spinRing1 {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes spinRing2 {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(-360deg); }
}

@keyframes spinRing3 {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

@keyframes rocketBounce {
  0%, 100% {
    transform: translateY(0px) scale(1);
  }
  50% {
    transform: translateY(-10px) scale(1.1);
  }
}

@keyframes textGlow {
  0%, 100% {
    background-position: 0% 50%;
    filter: drop-shadow(0 0 20px rgba(0, 234, 255, 0.5));
  }
  50% {
    background-position: 100% 50%;
    filter: drop-shadow(0 0 30px rgba(139, 92, 246, 0.7));
  }
}

@keyframes dotBounce {
  0%, 80%, 100% {
    transform: scale(1) translateY(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1.2) translateY(-10px);
    opacity: 1;
  }
}

@keyframes progressScan {
  0% { left: -100%; }
  100% { left: 100%; }
}

// 响应式设计
@media (max-width: 1400px) {
  .tech-dashboard {
    .stats-grid {
      grid-template-columns: repeat(3, 1fr);
    }
  }
}

@media (max-width: 1200px) {
  .tech-dashboard {
    .stats-grid {
      grid-template-columns: repeat(2, 1fr);
    }
  }
}

@media (max-width: 768px) {
  .tech-dashboard {
    padding: 10px;

    .gauges-container {
      flex-direction: column;

      .gauge-item {
        min-width: auto;
        max-width: none;
      }
    }

    .stats-grid {
      grid-template-columns: 1fr;
    }

    .chart-header {
      flex-direction: column;
      gap: 15px;
      align-items: flex-start !important;
    }
  }
}
</style>
